import setting from './setting'
import {Message} from 'element-ui';
import axios from 'axios';
import store from '../store'


// 创建 axios 实例
let service = axios.create(setting)

// 设置 post 默认 Content-Type
service.defaults.headers.post['Content-Type'] = 'application/json';

// 添加请求拦截器
service.interceptors.request.use((config) => {
    store.dispatch('SetLoading', true)
    if (localStorage.getItem('Xdh_token')) {
        config.headers.token = localStorage.getItem('Xdh_token');
    }
    //判断请求方式是否为POST，进行转换格式
    // console.log('config', config);
    /*   config.method === 'post' ?
           config.data = {...config.data }:
           config.params = {...config.params }; */
    // 请求发送前进行处理
    return config
    },
    (error) => {
        // 请求错误处理
        return Promise.reject(error)
    }
)

// 添加响应拦截器
service.interceptors.response.use((response) => {
        store.dispatch('SetLoading', false)
        if (response.data.success) {
            let {data} = response;
            return data;
        } else {
            Message.error(response.data.code + ":" + response.data.msg);
            return {};
        }
    },
    (error) => {
        store.dispatch('SetLoading', false)
        const {response} = error
        return Promise.reject(error)
        // let info = {},
        //     { status, statusText, data } = error.response;
        // //response为空时
        // if (!error.response) {
        //     Message.error("response为空,5000:" + 'Network Error');
        // } else {
        //     //报错
        //     Message.error(status + ":" + statusText);
        // }
    }
)


/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default service
